//
//  ConversationListTableViewCell.m
//  TIMChat
//
//  Created by AlexiChen on 16/2/18.
//  Copyright © 2016年 AlexiChen. All rights reserved.
//

#import "ConversationListTableViewCell.h"
#import "UIImageView+WebCache.h"
#import "FTAnimation.h"
#import "UILabel+Common.h"
#import "NSObject+FBKVOController.h"

@implementation ConversationListTableViewCell
- (void)dealloc
{
    [self.KVOController unobserveAll];
    //    self.KVOController = nil;
}

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier])
    {
        [self addOwnViews];
        //        [self configOwnViews];
        
        self.KVOController = [FBKVOController controllerWithObserver:self];
        self.backgroundColor = kClearColor;
    }
    return self;
}

- (void)addOwnViews
{
    _backView = [[UIView alloc] init];
    _backView.backgroundColor = KWhiteColor;
    _backView.layer.cornerRadius = 8;
    _backView.layer.masksToBounds = YES;
    [self.contentView addSubview:_backView];
    
    _conversationIcon = [[UIImageView alloc] init];
    _conversationIcon.backgroundColor = kWhiteColor;
    _conversationIcon.layer.cornerRadius = 25;
    _conversationIcon.layer.masksToBounds = YES;
    [self.contentView addSubview:_conversationIcon];
    
    _conversationName = [[UILabel alloc] init];
    _conversationName.font = kAppLargeTextFont;
    _conversationName.textColor = kBlackColor;
    [self.contentView addSubview:_conversationName];
    
    _lastMsgTime = [[UILabel alloc] init];
    _lastMsgTime.font = kAppSmallTextFont;
    _lastMsgTime.textAlignment = NSTextAlignmentRight;
    _lastMsgTime.textColor = RGB_HEX(0x909090);
    _lastMsgTime.adjustsFontSizeToFitWidth = YES;
    [self.contentView addSubview:_lastMsgTime];
    
    _lastMsg = [[UILabel alloc] init];
    _lastMsg.font = kAppSmallTextFont;
    _lastMsg.textColor = RGB_HEX(0x9395a2);
    [self.contentView addSubview:_lastMsg];
    
    _gradientLayer =  [CAGradientLayer layer];
    _gradientLayer.frame = CGRectMake(0, 0, 20, 20);
    _gradientLayer.startPoint = CGPointMake(0, 0);
    _gradientLayer.endPoint = CGPointMake(1, 1);
    _gradientLayer.locations = @[@(0.0),@(1.0)];//渐变点
    [_gradientLayer setColors:@[(id)[UIColor colorWithRed:255/255.0 green:2/255.0 blue:114/255.0 alpha:1.0].CGColor, (__bridge id)[UIColor colorWithRed:255/255.0 green:142/255.0 blue:142/255.0 alpha:1.0].CGColor]];//渐变数组
    _unReadBadge = [UIButton buttonWithType:UIButtonTypeSystem];
    _unReadBadge.layer.cornerRadius = 10;
    _unReadBadge.layer.masksToBounds = YES;
    [_unReadBadge setTitleColor:kWhiteColor forState:UIControlStateNormal];
    [_unReadBadge addTarget:self action:@selector(onClickUnRead:) forControlEvents:UIControlEventTouchUpInside];
    [_unReadBadge.layer addSublayer:_gradientLayer];
    [self.contentView addSubview:_unReadBadge];
}

- (void)onClickUnRead:(UIButton *)button
{
    IMAConversation *conv = (IMAConversation *)_showItem;
    [conv setReadAllMsg];
    
    NSInteger unReadCount = 0;
    [_unReadBadge setTitle:[NSString stringWithFormat:@"%ld", (long)unReadCount] forState:UIControlStateNormal];
   [_unReadBadge fadeOut:0.25 delegate:nil];
    
}

- (void)configOwnViews
{
    //    [_conversationIcon sd_setBackgroundImageWithURL:nil forState:UIControlStateNormal placeholderImage:[UIImage imageWithColor:kRandomFlatColor]];
    
    _conversationName.text = @"测试";
    
    _lastMsgTime.text = @"测试19:10";
    
    _lastMsg.text = @"这是一个测试消息";
    
    
    NSInteger unReadCount = 99;
    _unReadBadge.hidden = unReadCount == 0;
    
    [_unReadBadge setTitle:unReadCount > 99 ? @"99+" : [NSString stringWithFormat:@"%ld", (long)unReadCount] forState:UIControlStateNormal];
}


- (void) configCellWith:(id<IMAConversationShowAble>)item withUser:(IMAUser *)user
{
    _showItem = item;
    if ([item conversationType] == TIM_GROUP) {
        _conversationIcon.image = [UIImage imageNamed:@"conten_but_qunzu_default"];
        if (((IMAConversation *)item).nickName == nil) {
            [[TIMGroupManager sharedInstance] GetGroupInfo:@[user.userId] succ:^(NSArray *arr) {
                TIMGroupInfo *groupInfo = arr[0];
                _conversationName.text = groupInfo.groupName;
                ((IMAConversation *)item).nickName = groupInfo.groupName;
                
            } fail:^(int code, NSString *msg) {
                
            }];
        } else {
            _conversationName.text = ((IMAConversation *)item).nickName;
        }

    }else if ([item conversationType] == TIM_C2C){
        if (((IMAConversation *)item).nickName == nil || ((IMAConversation *)item).iconUrl == nil) {
            [[TIMFriendshipManager sharedInstance] GetUsersProfile:@[user.userId] succ:^(NSArray *friends) {
                for (TIMUserProfile *pro in friends)
                {
                    IMAUser *user1 = [[IMAUser alloc] initWithUserInfo:pro];
                    [_conversationIcon  sd_setImageWithURL:[NSURL URLWithString:user1.icon] placeholderImage:[UIImage imageNamed:@"bmh_default_avatar"]];
                    _conversationName.text = user1.nickName;
//                    if ([user1.userId isEqualToString:@"10000"]) {
//                        _conversationName.textColor = UIColorFromRGB(0xFF5F6D);
//                    }else{
                        _conversationName.textColor = kBlackColor;
//                    }
                    ((IMAConversation *)item).iconUrl = user1.icon;
                    ((IMAConversation *)item).nickName = user1.nickName;
                }
            } fail:^(int code, NSString *msg) {
                DebugLog(@"Failddd: %d->%@", code, msg);
            }];
        } else {
            [_conversationIcon  sd_setImageWithURL:[NSURL URLWithString:((IMAConversation *)item).iconUrl] placeholderImage:[UIImage imageNamed:@"bmh_default_avatar"]];
            _conversationName.text = ((IMAConversation *)item).nickName;
        }
    }
    NSLog(@"showIconUrlshowIconUrl == %@ == %@ == %@", user.icon, [_showItem showIconUrl],[_showItem showTitle]);
    
    [self.KVOController unobserveAll];
    [self relayoutFrameOfSubViews];
    
    __weak ConversationListTableViewCell *ws = self;
    [self.KVOController observe:item keyPath:@"lastMessage" options:NSKeyValueObservingOptionNew block:^(id observer, id object, NSDictionary *change) {
        [ws updateCellOnNewMessage];
    }];
    [self.KVOController observe:item keyPath:@"lastMessage.status" options:NSKeyValueObservingOptionNew block:^(id observer, id object, NSDictionary *change) {
        [ws updateCellOnNewMessage];
    }];
    
    [self.KVOController observe:item keyPath:@"draft" options:NSKeyValueObservingOptionNew block:^(id observer, id object, NSDictionary *change){
        [ws updateCellOnNewMessage];
    }];

    
    [self updateCellOnNewMessage];
}

- (void)refreshCell
{
    [self updateCellOnNewMessage];
}

- (void)updateCellOnNewMessage
{
    
    _lastMsgTime.text = [_showItem lastMsgTime];
    
#if kTestChatAttachment
    
    NSAttributedString *attributeDraft = [_showItem attributedDraft];
    _lastMsg.attributedText = attributeDraft.length ? attributeDraft : [_showItem lastAttributedMsg];
    
#else
    NSString *draft = [_showItem attributedDraft];
    _lastMsg.text = draft.length ? draft : [_showItem lastMsg];
#endif
    NSInteger unReadCount = [_showItem unReadCount];
    _unReadBadge.hidden = unReadCount == 0;
    [_unReadBadge setTitle:unReadCount > 99 ? @"99+" : [NSString stringWithFormat:@"%ld", (long)unReadCount] forState:UIControlStateNormal];
    if (unReadCount < 10) {
        [_gradientLayer setFrameSize:CGSizeMake(20, 20)];
        [_unReadBadge sizeWith:CGSizeMake(20, 20)];
    }else if (unReadCount > 9) {
        [_gradientLayer setFrameSize:CGSizeMake(30, 20)];
        [_unReadBadge sizeWith:CGSizeMake(30, 20)];
    }
    [_unReadBadge alignRight:_lastMsgTime];
    [_unReadBadge alignVerticalCenterOf:_lastMsg];

}

- (void)layoutSubviews
{
    [super layoutSubviews];
    [self relayoutFrameOfSubViews];
}

- (void)relayoutFrameOfSubViews
{
    [_backView sizeWith:CGSizeMake(ScreenWidth-20, 70)];
    [_backView layoutParentCenter];
    
    [_conversationIcon sizeWith:CGSizeMake(50, 50)];
    [_conversationIcon layoutParentVerticalCenter];
    [_conversationIcon alignParentLeftWithMargin:kDefaultMargin+10];
    
    [_lastMsgTime sizeWith:CGSizeMake(60, 28)];
    [_lastMsgTime alignParentRightWithMargin:kDefaultMargin+10];
    [_lastMsgTime alignTop:_conversationIcon];
    
    [_conversationName sameWith:_lastMsgTime];
    [_conversationName layoutToRightOf:_conversationIcon margin:kDefaultMargin];
    [_conversationName scaleToLeftOf:_lastMsgTime margin:kDefaultMargin];
    
    [_lastMsg sameWith:_conversationName];
    [_lastMsg layoutBelow:_conversationName];
    [_lastMsg scaleToBelowOf:_conversationIcon];
    
        if (_unReadBadge.titleLabel.text.length == 1)
        {
            [_gradientLayer setFrameSize:CGSizeMake(20, 20)];
            [_unReadBadge sizeWith:CGSizeMake(20, 20)];
        }else  {
            [_gradientLayer setFrameSize:CGSizeMake(30, 20)];
            [_unReadBadge sizeWith:CGSizeMake(30, 20)];
        }
    NSLog(@"leathhhthh == %@",_unReadBadge.titleLabel.text);

    [_unReadBadge alignRight:_lastMsgTime];
    [_unReadBadge alignVerticalCenterOf:_lastMsg];
}

//获取未读条数
- (NSInteger)getUnReadCount
{
    //获取未读条数
    NSInteger unReadCount = [_showItem unReadCount];
    
    return unReadCount;
}

//标记是否已读
- (void)markReaded
{
    //标记已经读取
    [self onClickUnRead:_unReadBadge];
}



@end
